package com.mc.read.common.util;

import com.aliyun.oss.OSSClient;
import com.mc.read.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author:LiuHao
 * @Date: Create in 17:10 2018/4/4
 **/

/**
 * 阿里云 OSS文件类
 *
 * @author YuanDuDu
 */
@Slf4j
public class OSSClientUtil {
    private String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    // accessKey
    private String accessKeyId = "LTAI0b3xL1BpjE0j";
    private String accessKeySecret = "4T0Fc1KU1z33CDb3wtFqfM5f636Ay5";
    //空间
    private String bucketName = "mc-read";
    //文件存储目录
    private String filedir = "pic/";

    private OSSClient ossClient;

    public OSSClientUtil() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 初始化
     */
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 销毁
     */
    public void destory() {
        ossClient.shutdown();
    }

    /**
     * 上传图片
     *
     * @param url
     */
    public void uploadImg2Oss(String url) throws ServiceException {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadFile2OSS(fin, split[split.length - 1]);
        } catch (FileNotFoundException e) {
            throw new ServiceException(999, "图片上传失败");
        }
    }


    public String uploadImg2Oss(MultipartFile file) throws ServiceException {
        try {
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            String name = UUID.randomUUID() + substring;
            InputStream inputStream = file.getInputStream();
            String url = this.uploadFile2OSS(inputStream, name);
            return url;
        } catch (Exception e) {
            throw new ServiceException(999, "图片上传失败");
        } finally {
            ossClient.shutdown();
        }
    }


    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return this.getUrl(this.filedir + split[split.length - 1]);
        }
        return null;
    }

    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(InputStream instream, String fileName) {
        String ret = "";
        try {
//            //创建上传Object的Metadata
//            ObjectMetadata objectMetadata = new ObjectMetadata();
//            objectMetadata.setContentLength(instream.available());
//            objectMetadata.setCacheControl("no-cache");
//            objectMetadata.setHeader("Pragma", "no-cache");
//            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
//            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
            filedir = filedir + today + "/" + fileName;
//           ossClient.putObject(bucketName, filedir, instream, objectMetadata);


            ossClient.putObject(bucketName, filedir, instream);
            ret = "http://mc-read.oss-cn-beijing.aliyuncs.com/" + filedir;

        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            ossClient.shutdown();
        }
        return ret;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }

        return "image/jpeg";
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    /**
     * @Author:LiuHao
     * @Date:14:47 2018/8/2
     * 删除文件
     **/
    public void deleteFile(String fileName) throws ServiceException {
        try {
            ossClient.deleteObject(bucketName, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(999, "删除文件失败，请重试");
        } finally {
            ossClient.shutdown();
        }

    }
    public String uploadImgForUrl(String fileUrl) throws ServiceException {
        try {
            URL url=new URL(fileUrl);
            URLConnection urlConn = url.openConnection();
            InputStream input = urlConn.getInputStream();
            String file = urlConn.getURL().getFile();
            String filename = file.substring(file.lastIndexOf('/')+1);
            String substring = filename.substring(filename.lastIndexOf(".")).toLowerCase();
            String name = UUID.randomUUID()+substring;
            String url1 = this.uploadFile2OSS(input, name);
            return url1;
        } catch (Exception e) {
            throw new ServiceException(999, "图片上传失败");
        } finally {
            ossClient.shutdown();
        }
    }

}